#include "symbol_table.h"
#include <malloc.h>
#include <string.h>
#include <gdsl/gdsl_list.h>

struct symbolSize
{
    symbol_type type;
	int size;
} symbol_size[]={
	{SYMBOL_INT,sizeof(int)},
	{SYMBOL_STRING,sizeof(void*)},
};

static void free_symbol(gdsl_element_t temp)
{
	symbol* e=(symbol*)temp;
	if(e){
		if(e->name)
			free(e->name);
		if(e->content)
			free(e->content);
		free(e);
	}
}
static void* symbol_alloc_content(symbol_type type)
{
	int i;
	int length=sizeof(symbol_size);
	if(type<SYMBOL_MAX_TYPE && type>SYMBOL_MIN_TYPE){
		for(i=0;i<length;i++)
			if (symbol_size[i].type==type)
				{
					return malloc(symbol_size[i].size);
				}
	}
	else
		return NULL;
}
symbol* symbol_create(char* name,symbol_type type)
{
	char* ctemp;
	void* vtemp;
	symbol* e=(symbol*)malloc(sizeof(symbol));
	if(ctemp=strdup(name))
		e->name=ctemp;
	else
		return NULL;
	if(vtemp=symbol_alloc_content(type))
		e->content=vtemp;
	else{
		free(e->name);
		return NULL;
	}
	e->type=type;
	return e;
}
symbol_table symbol_table_init(void)
{
	gdsl_list_t l=gdsl_list_alloc("symbol_table",NULL,free_symbol);
	return (symbol_table)l;
}
void symbol_table_destroy(symbol_table t)
{
	gdsl_list_free((gdsl_list_t)t);
}
symbol* symbol_table_add(symbol_table t,symbol* s)
{
	gdsl_list_insert_tail((gdsl_list_t)t,s);
}
long int compare_name(gdsl_element_t e,void* cname)
{
	char* name=(char*)cname;
	symbol* tmp =(symbol*)e;
	return strcmp(tmp->name,name);
}
symbol* symbol_table_get(symbol_table t,char *name)
{
	gdsl_element_t e;
	e=gdsl_list_search((gdsl_list_t)t,compare_name,name);
	return (symbol*)e;

}
symbol_table symbol_table_delete(symbol_table t,char* name)
{
	return (symbol_table)gdsl_list_delete((gdsl_list_t)t,compare_name,name);
}
